//package com.example.casper.Experiment2024;
//
//import android.os.Bundle;
//
//import androidx.fragment.app.Fragment;
//
//import android.view.LayoutInflater;
//import android.view.View;
//import android.view.ViewGroup;
//
///**
// * A simple {@link Fragment} subclass.
// * Use the {@link ShoppingListFragment#newInstance} factory method to
// * create an instance of this fragment.
// */
//public class ShoppingListFragment extends Fragment {
//
//    // TODO: Rename parameter arguments, choose names that match
//    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
//    private static final String ARG_PARAM1 = "param1";
//    private static final String ARG_PARAM2 = "param2";
//
//    // TODO: Rename and change types of parameters
//    private String mParam1;
//    private String mParam2;
//
//    public ShoppingListFragment() {
//        // Required empty public constructor
//    }
//
//    /**
//     * Use this factory method to create a new instance of
//     * this fragment using the provided parameters.
//     *
//     * @param param1 Parameter 1.
//     * @param param2 Parameter 2.
//     * @return A new instance of fragment ShoppingListFragment.
//     */
//    // TODO: Rename and change types and number of parameters
//    /*String param1, String param2*/
//    public static ShoppingListFragment newInstance() {
//        ShoppingListFragment fragment = new ShoppingListFragment();
//        Bundle args = new Bundle();
//        //args.putString(ARG_PARAM1, param1);
//        //args.putString(ARG_PARAM2, param2);
//        fragment.setArguments(args);
//        return fragment;
//    }
//
//    @Override
//    public void onCreate(Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//        if (getArguments() != null) {
//            //mParam1 = getArguments().getString(ARG_PARAM1);
//            //mParam2 = getArguments().getString(ARG_PARAM2);
//        }
//    }
//
//    @Override
//    public View onCreateView(LayoutInflater inflater, ViewGroup container,
//                             Bundle savedInstanceState) {
//        // Inflate the layout for this fragment
//        View rootViewer = inflater.inflate(R.layout.fragment_shopping_list)
//        return inflater.inflate(R.layout.fragment_shopping_list, container, false);
//    }
//    private ArrayList<BookItem> items;
//    ActivityResultLauncher<Intent> addItemLauncher;
//    ActivityResultLauncher<Intent> updateItemLauncher;
//    private BookItemAdapter b=new BookItemAdapter(items);;
//
//
//    @Override
//    public boolean onContextItemSelected(MenuItem item) {
//
//        switch (item.getItemId()) {
//            case 0:
//                Intent intent = new Intent(Hello1826Activity.this, BookItemDetailActivity.class);
//                addItemLauncher.launch(intent);
//                break;
//            case 1:
//                AlertDialog.Builder builder = new AlertDialog.Builder(this);
//                builder.setTitle("Delete Data");
//                builder.setMessage("Are you sure you want to delete this data?");
//                builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        items.remove(item.getOrder());
//                        b.notifyItemRemoved(item.getOrder());
//                        b.notifyDataSetChanged();
//                        DataBank databank =new DataBank(Hello1826Activity.this);
//                        databank.SaveBookItems(items);
//
//                    }
//                });
//                builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        dialog.dismiss();
//                    }
//                });
//                builder.create().show();
//                break;
//            case 2:
//                Intent intentUpdate = new Intent(Hello1826Activity.this, BookItemDetailActivity.class);
//                BookItem shopItem= items.get(item.getOrder());
//                intentUpdate.putExtra("name",shopItem.getName());
//                intentUpdate.putExtra("price",shopItem.getPrice());
//                intentUpdate.putExtra("position",item.getOrder());
//                updateItemLauncher.launch(intentUpdate);
//                break;
//            default:
//                return super.onContextItemSelected(item);
//        }
//        return true;
//    }
//    @SuppressLint("NotifyDataSetChanged")
//    @Override
//    protected void onCreate(Bundle savedInstanceState) {
//        addItemLauncher = registerForActivityResult(
//                new ActivityResultContracts.StartActivityForResult(),
//                result -> {
//                    if (result.getResultCode() == Activity.RESULT_OK) {
//                        Intent data = result.getData();
//                        assert data!=null;
//                        String name = data.getStringExtra("name"); // 获取返回的数据
//                        String priceText = data.getStringExtra("price"); // 获取返回的数据
//
//                        double price= Double.parseDouble(priceText);
//                        items.add(new BookItem(name, price, R.drawable.pic1));
//                        b.notifyItemInserted(items.size()-1);
//                        b.notifyDataSetChanged();
//                        DataBank databank =new DataBank(Hello1826Activity.this);
//                        databank.SaveBookItems(items);
//
//                    } else if (result.getResultCode() == Activity.RESULT_CANCELED) {
//                        // 处理取消操作
//                    }
//                }
//        );
//        updateItemLauncher = registerForActivityResult(
//                new ActivityResultContracts.StartActivityForResult(),
//                result -> {
//                    if (result.getResultCode() == Activity.RESULT_OK) {
//                        Intent data = result.getData();
//                        assert data !=null;
//                        int position = data.getIntExtra("position",0);
//                        String name = data.getStringExtra("name"); // 获取返回的数据
//                        String priceText = data.getStringExtra("price"); // 获取返回的数据
//
//                        double price= Double.parseDouble(priceText);
//                        BookItem shopItem = items.get(position);
//                        shopItem.setPrice(price);
//                        shopItem.setName(name);
//                        b.notifyItemChanged(position);
//                        b.notifyDataSetChanged();
//                        DataBank databank =new DataBank(Hello1826Activity.this);
//                        databank.SaveBookItems(items);
//
//                    } else if (result.getResultCode() == Activity.RESULT_CANCELED) {
//                        // 处理取消操作
//                    }
//                }
//        );
//        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_hello1826);
//
//
//
//        items = new ArrayList<>();
//        DataBank databank =new DataBank(this);
//        items = databank.readItems();
//        if(items.isEmpty())
//            items.add(new BookItem("信息安全数学基础（第2版）",1.0, R.drawable.pic3));
//        //        items.add(new BookItem("创新工程实践",4.0, R.drawable.pic1));
//        //        items.add(new BookItem("软件项目管理案例教程（第3版）",3.0, R.drawable.pic2));
//        //        items.add(new BookItem("信息安全数学基础（第2版）",1.0, R.drawable.pic3));
//        //for (int i = 0; i < 5; i++)
//        //    items.add(new BookItem("信息安全数学基础（第2版）",1.0, R.drawable.pic3));
//            /*for(int i=0;i<3;++i){
//
//            }*/
//            RecyclerView mainRecyclerView = findViewById(R.id.recycler_view_the_books);
//            mainRecyclerView.setLayoutManager(new LinearLayoutManager(this));
//
//            BookItemAdapter BookItemAdapter = new BookItemAdapter(items);
//            mainRecyclerView.setAdapter(BookItemAdapter);
//
//            registerForContextMenu(mainRecyclerView);
//
//            ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
//                Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
//                v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
//                return insets;
//            });
//        }
//
//        private  class BookItemAdapter extends RecyclerView.Adapter {
//
//            private final List<BookItem> items;
//
//            public BookItemAdapter(List<BookItem> items) {
//                this.items = items;
//            }
//
//            @NonNull
//            @Override
//            public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
//                View view = LayoutInflater.from(parent.getContext())
//                        .inflate(R.layout.recycle_1826, parent, false);
//                return new MyViewHolder(view);
//            }
//
//            @Override
//            public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
//                MyViewHolder myViewHolder = (MyViewHolder) holder;
//                myViewHolder.getTextViewName().setText(items.get(position).getName());
//                //myViewHolder.getTextViewPrice().setText(""+items.get(position).getPrice());
//                myViewHolder.getImageViewPicture().setImageResource(items.get(position).getImageResourceId());
//
//            }
//
//            @Override
//            public int getItemCount() {
//                return items.size();
//            }
//        }
//
//        private class MyViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener {
//            public ImageView getImageViewPicture() {
//                return imageViewPicture;
//            }
//
//            public TextView getTextViewName() {
//                return textViewName;
//            }
//
//            public TextView getTextViewPrice() {
//                return textViewPrice;
//            }
//
//            private final ImageView imageViewPicture;
//
//            private final TextView textViewName;
//
//            private final TextView textViewPrice;
//
//            //private final TextView textViewPrice;
//
//            public MyViewHolder(@NonNull View itemView) {
//                super(itemView);
//                this.imageViewPicture = itemView.findViewById(R.id.image_view_book_cover);
//                this.textViewName = itemView.findViewById(R.id.textview_item_name);
//                this.textViewPrice = itemView.findViewById(R.id.textview_item_price);
//
//                itemView.setOnCreateContextMenuListener(this);
//            }
//
//            @Override
//            public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
//                menu.setHeaderTitle("具体操作");
//
//                menu.add(0, 0, this.getAdapterPosition(), "添加" + this.getAdapterPosition());
//                menu.add(0, 1, this.getAdapterPosition(), "删除" + this.getAdapterPosition());
//                menu.add(0, 2, this.getAdapterPosition(), "修改" + this.getAdapterPosition());
//            }
//        }
//}
package com.example.casper.Experiment2024;


import android.app.Activity;
import android.app.AlertDialog;
import android.content.ClipData;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.casper.Experiment2024.data.BookItem;
import com.example.casper.Experiment2024.data.DataBank;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
//import com.example.casper.Experiment2024.data.Item;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link ShoppingListFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ShoppingListFragment extends Fragment {


    public ShoppingListFragment() {
        // Required empty public constructor
    }

    private ArrayList<BookItem> items;
    private ActivityResultLauncher<Intent> launcherAdd;
    private ActivityResultLauncher<Intent> launcherUpdate;
    private ShopItemAdapter shopItemAdapter;

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @return A new instance of fragment ShoppingListFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static ShoppingListFragment newInstance() {
        ShoppingListFragment fragment = new ShoppingListFragment();
        Bundle args = new Bundle();
        //args.putString(ARG_PARAM1, param1);
        //args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootViewer = inflater.inflate(R.layout.fragment_shopping_list, container, false);

        RecyclerView mainRecyclerView = rootViewer.findViewById(R.id.recyclerview_items);
        mainRecyclerView.setLayoutManager(new LinearLayoutManager(this.getContext()));
        DataBank databank=new DataBank(this.getContext());

        FloatingActionButton add_button = rootViewer.findViewById(R.id.floatingActionButton_1826);
        add_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 在这里处理按钮点击事件
                Intent intentAdd = new Intent(getActivity(), BookItemDetailActivity.class);
                //intentAdd.putExtra("position", itemMenu.getOrder());
                intentAdd.putExtra("position", 0);
                launcherAdd.launch(intentAdd);
            }
        });
        items= databank.readItems();
        if(items.isEmpty())
            items.add(new BookItem("book1","It's very happy" ,R.drawable.pic1));


        shopItemAdapter = new ShopItemAdapter(items);
        mainRecyclerView.setAdapter(shopItemAdapter);

        registerForContextMenu(mainRecyclerView);
        return rootViewer;
    }

    @Override
    public boolean onContextItemSelected(MenuItem itemMenu ) {
        //item.getOrder()
        switch (itemMenu.getItemId()) {
            case 0:
                Intent intentAdd = new Intent(this.getContext(), BookItemDetailActivity.class);
                intentAdd.putExtra("position", itemMenu.getOrder());
                launcherAdd.launch(intentAdd);
                break;
            case 1:
                AlertDialog.Builder builder = new AlertDialog.Builder(this.getContext());
                builder.setTitle(R.string.confirmation)
                        .setMessage(R.string.are_you_sure_you_want_to_delete_the_item)
                        .setPositiveButton(R.string.yes, (dialog, id) -> {
                            items.remove(itemMenu.getOrder());
                            shopItemAdapter.notifyItemRemoved(itemMenu.getOrder());
                            DataBank databank=new DataBank(ShoppingListFragment.this.getContext());
                            //databank.SaveBookItems(items);
                            databank.saveItems(items);
                        })
                        .setNegativeButton(R.string.no, (dialog, id) -> {
                            // 用户取消删除
                            dialog.dismiss();
                        });
                // 创建并显示对话框
                AlertDialog dialog = builder.create();
                dialog.show();
                break;
            case 2:
                Intent intentUpdate = new Intent(ShoppingListFragment.this.getContext(), BookItemDetailActivity.class);
                intentUpdate.putExtra("position", itemMenu.getOrder());
                BookItem itemObject= items.get(itemMenu.getOrder());
                intentUpdate.putExtra("item_name", itemObject.getTitle());
                intentUpdate.putExtra("item_data", itemObject.getContext_daka());
                launcherUpdate.launch(intentUpdate);
                break;
            default:
                return super.onContextItemSelected(itemMenu);
        }
        return true;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //mParam1 = getArguments().getString(ARG_PARAM1);
        //mParam2 = getArguments().getString(ARG_PARAM2);
        launcherAdd = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == Activity.RESULT_OK) {
                        Intent data = result.getData();
                        assert data != null;
                        String itemName=data.getStringExtra("item_name");
                        String item_data=data.getStringExtra("item_data");
                        int position = data.getIntExtra("position",0);
                        items.add(position,new BookItem(itemName, item_data, R.drawable.pic3));
                        shopItemAdapter.notifyItemInserted(position);
                        DataBank databank=new DataBank(this.getContext());
                        //databank.SaveBookItems(items);
                        databank.saveItems(items);
                    }
                });
        launcherUpdate = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == Activity.RESULT_OK) {
                        Intent data = result.getData();
                        assert data != null;
                        String itemName = data.getStringExtra("item_name");
                        String itemData = data.getStringExtra("item_data");
                        int position = data.getIntExtra("position", 0);
                        BookItem item = items.get(position);
                        item.setTitle(itemName);
                        item.setContext_daka(itemData);
                        shopItemAdapter.notifyItemChanged(position);
                        DataBank databank=new DataBank(this.getContext());
                        //databank.SaveBookItems(items);
                        databank.saveItems(items);
                    }
                });


    }

    private static class ShopItemAdapter extends RecyclerView.Adapter {
        private final List<BookItem> items;

        public ShopItemAdapter(List<BookItem> items) {
            this.items=items;
        }

        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.recycle_1826, parent, false);
            return new MyViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
            MyViewHolder myViewHolder= (MyViewHolder) holder;
            myViewHolder.getTextViewName().setText(items.get(position).getTitle());
            myViewHolder.getTextViewData().setText(items.get(position).getContext_daka());
            myViewHolder.getImageViewPicture().setImageResource(items.get(position).getResourceId());
        }

        @Override
        public int getItemCount() {
            return items.size();
        }

        private class MyViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener {
            public ImageView getImageViewPicture() {
                return imageViewPicture;
            }

            public TextView getTextViewName() {
                return textViewName;
            }

            public TextView getTextViewData() {
                return textViewData;
            }

            //public TextView getTextViewPrice() {
            //    return textViewPrice;
            //}

            private final ImageView imageViewPicture;
            private final TextView textViewName;
            //private final TextView textViewPrice;
            private final TextView textViewData;

            public MyViewHolder(@NonNull View itemView) {
                super(itemView);
                this.imageViewPicture= itemView.findViewById(R.id.image_view_book_cover);
                this.textViewName= itemView.findViewById(R.id.textview_item_name);
                this.textViewData = itemView.findViewById(R.id.textview_item_data);
                //this.textViewPrice=itemView.findViewById(R.id.textview_item_price);

                itemView.setOnCreateContextMenuListener(this);
            }

            @Override
            public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
                menu.setHeaderTitle("具体操作");

                menu.add(0, 0, this.getAdapterPosition(), "添加" + this.getAdapterPosition());
                menu.add(0, 1, this.getAdapterPosition(), "删除" + this.getAdapterPosition());
                menu.add(0, 2, this.getAdapterPosition(), "修改" + this.getAdapterPosition());
            }
        }
    }

}